package timing.ukulele.auth.security.type.image;

import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import timing.ukulele.auth.security.user.TimingUserDetailService;

public class ImageCodeAuthenticationProvider implements AuthenticationProvider {

    private final TimingUserDetailService userService;
    private final PasswordEncoder passwordEncoder;

    public ImageCodeAuthenticationProvider(TimingUserDetailService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ImageCodeAuthenticationToken authenticationToken = (ImageCodeAuthenticationToken) authentication;
        UserDetails user = userService.loadUserByUsername((String) authenticationToken.getPrincipal());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        if (ObjectUtils.isEmpty(authentication.getCredentials())) {
            throw new AuthenticationCredentialsNotFoundException("密码不能为空");
        }
        String password = (String) authentication.getCredentials();
        // TODO 锁定，过期等
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        ImageCodeAuthenticationToken result = new ImageCodeAuthenticationToken(user, user.getAuthorities());
        result.setDetails(authenticationToken.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return ImageCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}